package com.example.reagent_management.ui.statistics.helper

import android.R
import android.content.Context
import android.graphics.Color
import androidx.core.content.ContextCompat
import com.example.lib_base.utils.weak
import com.example.reagent_management.ui.statistics.pojo.OperateTimesAndNum
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.utils.ColorTemplate
import com.github.mikephil.charting.data.LineData


/*=================================== BarChart ==================================*/
/**
 * 柱状图基础设置
 */
fun initBarChart(barChart: BarChart?) {
    if (barChart != null) {
        barChart.setDrawValueAboveBar(true)
        barChart.setTouchEnabled(true)
        barChart.isDragEnabled = true
        barChart.setScaleEnabled(false)   //缩放 点击 触摸
        barChart.setNoDataText("暂无数据...") //没有数据显示内容
        barChart.setDrawGridBackground(false)
        //            Description description = new Description();
//            description.setText("");
        barChart.description.isEnabled = false //隐藏右下角英文 //设置描述 不能为空
        barChart.axisLeft.setDrawGridLines(false) //不设置Y轴网格
        barChart.axisRight.isEnabled = false //右侧不显示Y轴
        barChart.axisLeft.axisMinimum = 0f //设置Y轴显示最小值，不然0下面会有空隙
        //            barChart.setOnChartValueSelectedListener(this);
//        val legend = barChart.legend;
//        legend.setDrawInside(true); // 设置图例在图中
//        legend.orientation = Legend.LegendOrientation.VERTICAL; // 图例的方向为垂直
//        legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT; //显示位置，水平右对齐
//        legend.verticalAlignment = Legend.LegendVerticalAlignment.TOP; // 显示位置，垂直上对齐
        val xAxis = barChart.xAxis
        //设置X轴的值的间隔，具体不同看下面的图
        xAxis.granularity = 1f
        xAxis.setDrawGridLines(false) //与x轴垂直的线
        xAxis.setCenterAxisLabels(false)
        xAxis.position = XAxis.XAxisPosition.BOTTOM //x轴设在下方
//        xAxis.axisMaximum = 5F;   //X轴最大数值
//        xAxis.axisMinimum = 0F;   //X轴最小数值
        //X轴坐标的个数    第二个参数一般填false     true表示强制设置标签数 可能会导致X轴坐标显示不全等问题
        xAxis.setLabelCount(5, false)

        //设置y轴
        val yAxis = barChart.axisLeft
        yAxis.granularity = 1f
        //x y轴宽度，有时绘制不出来自行调整
        xAxis.axisLineWidth = 0.8f
        yAxis.maxWidth = 10f

    }
}

/**
 * 柱状图数据
 */
fun refreshBarData(
    barChart: BarChart?,
    yValues: List<BarEntry>,
    xValues: Array<String>,
    context: Context
) {
    val set: BarDataSet
    val mContext by weak { context }
    if (barChart != null && mContext != null) {

        if (barChart.data != null && barChart.data.dataSetCount > 0) {
            set = barChart.data.getDataSetByIndex(0) as BarDataSet
            set.values = yValues
            if (set.entryCount == 1) {
                barChart.data.barWidth = 0.3f   //柱形图宽度
            } else {
                barChart.data.barWidth = 0.5f
            }
            barChart.data.notifyDataChanged()
            barChart.notifyDataSetChanged()
        } else {
            set = BarDataSet(yValues, "试剂名")
            set.setDrawIcons(false)
            val xAxis = barChart.xAxis
            xAxis.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    val index = value.toInt()
                    return if (index <= xValues.size && xValues.isNotEmpty() && index != -1) {
                        xValues[index - 1]
                    } else ""
                }
            }
            val colors = ArrayList<Int>()
            val startColor1 =
                ContextCompat.getColor(mContext!!, R.color.holo_orange_light)
            val startColor2 = ContextCompat.getColor(mContext!!, R.color.holo_blue_light)
            val startColor3 = ContextCompat.getColor(mContext!!, R.color.holo_purple)
            val startColor4 =
                ContextCompat.getColor(mContext!!, R.color.holo_green_light)
            val startColor5 = ContextCompat.getColor(mContext!!, R.color.holo_red_light)
            colors.add(startColor1)
            colors.add(startColor2)
            colors.add(startColor3)
            colors.add(startColor4)
            colors.add(startColor5)
            set.colors = colors


            val dataSets = ArrayList<IBarDataSet>()
            dataSets.add(set)
            val data = BarData(dataSets)
            data.setValueTextSize(10f)
            //                data.setValueTypeface(tfLight);  //设置ttf字体文件
            if (set.entryCount == 1) {
                data.barWidth = 0.3f   //柱形图宽度
            } else {
                data.barWidth = 0.5f
            }
            barChart.data = data
        }
        barChart.invalidate()
    }
}


/*======================== LineChart ================================*/
/**
 * 折线图初始化
 */
fun initLineChart(chart: LineChart) {
    chart.setDrawBorders(false) //显示边界
    chart.setTouchEnabled(true)
    chart.isDragEnabled = true  //
    chart.setScaleEnabled(false)  //同时缩放 x y
    chart.setPinchZoom(true)
    chart.isDoubleTapToZoomEnabled = false  //是否双击进行缩放

    chart.isScaleXEnabled = true  //缩放x
//    chart.scaleX = 1.5f   //缩放比例

    chart.setNoDataText("暂无数据...")
    //得到X轴
    val xAxis: XAxis = chart.xAxis
    //设置X轴的位置（默认在上方)
    xAxis.position = XAxis.XAxisPosition.BOTTOM
    //设置X轴坐标之间的最小间隔
//    xAxis.granularity = 1f
    //设置X轴的值（最小值、最大值、然后会根据设置的刻度数量自动分配刻度显示）
//    xAxis.axisMinimum = 0f
    //不显示网格线
    xAxis.setDrawGridLines(false)
    // 标签倾斜
//    xAxis.labelRotationAngle = 45F
    //得到Y轴
    val yAxis: YAxis = chart.axisLeft
    val rightYAxis: YAxis = chart.axisRight
    //设置Y轴是否显示
    rightYAxis.isEnabled = false; //右侧Y轴不显示
    //不显示网格线
    yAxis.setDrawGridLines(false);
    //设置Y轴坐标之间的最小间隔
    yAxis.granularity = 1F
    //不显示描述
    chart.description.isEnabled = false
    //x y轴宽度，有时绘制不出来自行调整
    xAxis.axisLineWidth = 0.8f
    yAxis.maxWidth = 10f
}

/**
 *  刷新折线图数据
 *  week为true hour为false
 *  @param operateType
 *  @param weekOrHour
 */
fun refreshLineData(
    chart: LineChart,
    yValues1: List<Entry>,
    operateType: Boolean,
    weekOrHour: Boolean
) {
    val set1: LineDataSet
    if (chart.data != null && chart.data.dataSetCount > 0) {
        set1 = chart.data.getDataSetByIndex(0) as LineDataSet
        set1.values = yValues1
        chart.data.notifyDataChanged()
        chart.notifyDataSetChanged()
    } else {
        if (operateType) {
            set1 = LineDataSet(yValues1, "入库")
            set1.color = ColorTemplate.getHoloBlue()
            set1.fillColor = ColorTemplate.getHoloBlue()
        } else {
            set1 = LineDataSet(yValues1, "出库")
            set1.color = Color.RED
            set1.fillColor = Color.RED
        }
        set1.setDrawCircles(true);

        set1.setDrawValues(false)   //每个点的y值
        set1.lineWidth = 1.6f
        set1.mode = LineDataSet.Mode.LINEAR
        set1.setDrawCircleHole(false)   // 设置数据点是空心还是实心，默认空心
        //设置显示十字线，必须显示十字线，否则MarkerView不生效
        set1.isHighlightEnabled = true
//        chart.setScaleMinima(1.5f, 1.0f)  //初始化缩放比

        //设置x轴间隔
        val xAxis: XAxis = chart.xAxis
        if (weekOrHour) {
//            xAxis.granularity = 86400f
            xAxis.setLabelCount(7, false)
            xAxis.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
//                    return (value.toInt() / 86400).toString() + "日"
                    return ""
                }
            }
        } else {
//            xAxis.granularity = 3600f
//            xAxis.axisMinimum = 0f
            xAxis.setLabelCount(24, false)
            xAxis.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
//                    return (value.toInt() / 3600).toString() + "H"
                    return ""
                }
            }
        }

        val lineData = LineData() //设置数据
        lineData.addDataSet(set1)
        chart.data = lineData
    }
    chart.invalidate()
}